package com.example.homework

import android.os.Bundle
import android.text.Editable
import android.widget.EditText
import android.widget.TextView
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.example.homework.databinding.ActivityMainBinding
import com.example.homework.repositories.DataRepository
import com.google.android.material.snackbar.Snackbar

class MainActivity : AppCompatActivity() {
    private var _binding: ActivityMainBinding? = null
    val binding: ActivityMainBinding
        get() = _binding!!
    private lateinit var repository: DataRepository
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        _binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)
        repository = DataRepository(this)
        val inputEditText: EditText = binding.inputEditText
        val resultTextView: TextView = binding.resultTextView
        val setResultText: (String) -> Unit = { text: String -> resultTextView.text = text }
        resultTextView.text = repository.getTextFromCache()
        var inputText: String = ""
        binding.saveButton.setOnClickListener {
            inputText = inputEditText.text.toString()
            if (inputText != "") {
                repository.saveText(inputText)
                setResultText(repository.getTextFromCache())
                inputEditText.setText("")
            } else {
                Snackbar.make(binding.root, getString(R.string.provide_some_data), Snackbar.LENGTH_LONG).show()
            }
        }
        binding.clearButton.setOnClickListener {
            repository.clearText()
            setResultText(repository.getTextFromCache())
        }
        binding.saveDataToFile.setOnClickListener {
            inputText = inputEditText.text.toString()
            if (inputText != "") {
                repository.writeDataToFile(inputText)
                setResultText(repository.getTextFromFile())
                inputEditText.setText("")
            } else {
                Snackbar.make(binding.root, getString(R.string.provide_some_data), Snackbar.LENGTH_LONG).show()
            }
        }
        binding.clearDataFromFile.setOnClickListener {
            repository.clearDataFromFile()
            setResultText(repository.getTextFromFile())
        }
        binding.getDataFromCache.setOnClickListener {
            setResultText(repository.getTextFromCache())
        }
        binding.getDataFromFile.setOnClickListener {
            setResultText(repository.getTextFromFile())
        }
    }
}